import sqlite3
import requests
from datetime import datetime


def get_db():
    return sqlite3.connect("./db/wx_data.db")


def has_user(openid):
    db_con = get_db()
    cur = db_con.cursor()
    data = cur.execute("SELECT * FROM `user` WHERE `openid` = ?", (openid,))
    db_con.commit()
    row = data.fetchone()
    cur.close()
    db_con.close()
    if row == None:
        return False
    else:
        return True


def add_user(openid, nick, token):
    db_con = get_db()
    #time_now = int(datetime.now().timestamp())
    cur = db_con.cursor()
    cur.execute("INSERT INTO `user` (nickname, openid, token, exp, checked_day, last_update_time, last_check_time) VALUES(?,?,?,?,?,?,?)", (nick, openid, token, 0, 0, 0, 0))
    db_con.commit()
    cur.close()
    db_con.close()


def get_user(openid):
    db_con = get_db()
    cur = db_con.cursor()
    data = cur.execute("SELECT * FROM `user` WHERE `openid` = ?", (openid,))
    db_con.commit()
    row = data.fetchone()
    cur.close()
    db_con.close()
    return row


def check(openid, exp):
    db_con = get_db()
    cur = db_con.cursor()
    data = cur.execute("""SELECT checked_day, exp FROM `user` WHERE `openid` = ?""", (openid,))
    data = data.fetchone()
    
    checked_day = int(data[0])
    exp_now = int(data[1])

    checked_day += 1
    exp_now += exp

    time_now = datetime.now().timestamp()
    cur.execute("""UPDATE  `user` SET exp=?, checked_day=?, last_check_time=?  WHERE `openid` = ?""",
                (exp_now, checked_day, time_now, openid))
    db_con.commit()
    cur.close()
    db_con.close()


def get_last_check_time(openid):
    db_con = get_db()
    cur = db_con.cursor()
    data = cur.execute("""SELECT * FROM `user` WHERE `openid` = ?""", (openid,))
    db_con.commit()
    row = data.fetchone()
    db_con.close()
    return row[7]
